<template>
  <el-drawer
    :model-value="showDrawer"
    :title="drawerTitle"
    direction="btt"
    size="100%"
    :close-on-press-escape="false"
    :before-close="closeDrawer"
    @close="closeDialog"
  >
    <div class="btn-list">
      <el-button
        type="primary"
        size="default"
        @click.stop="handleSave()"
        class="right ml-2"
        :loading="loading"
      >保存</el-button>
      <el-upload
        ref="upload"
        action="#"
        :limit="1"
        :before-upload="uploadBefore"
        :auto-upload="true"
        :show-file-list="false"
        :on-exceed="handleExceed"
        class="right"
        style="width:56px"
      >
        <el-button size="default">导入</el-button>
      </el-upload>
    </div>
    <MdEditor
      v-if="showDrawer"
      v-model="text"
      editor-class="md-detail-view isEdit"
      :toolbars="toolbars"
      @onUploadImg="onUploadImg"
      @onSave="saveMdFile"
    />
  </el-drawer>
</template>
<script>

import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
export default {
  emits: ['setFile', 'closeDialog'],
  props: {
    fileId: {
      type: String,
      default: ''
    },
    concatIdList: {
      type: String,
      default: ''
    },
    showDrawer: {
      type: Boolean,
      default: false
    },
    drawerTitle: {
      type: String,
      default: '编辑实验手册'
    },
  },
  components: {
    MdEditor
  },
  watch: {
    showDrawer: {
      handler (val) {
        if (val) {
          if (this.fileId) {
            let that = this
            this.fileObject.getFileContent(this.fileId).then(res => {
              that.defaultText = res.data
              that.text = res.data
            })
          } else {
            this.text = ''
            this.defaultText = ''
          }
        }
      },
      immediate: true
    }
  },
  data () {
    return {
      loading: false,
      concatIds: [],
      defaultText: '',
      text: '',
      toolbars: [
        'bold',                         // '加粗',
        'underline',                    //'下划线',
        'italic',                       //'斜体',
        'strikeThrough',                //'删除线',
        'sub',                          //'下标',
        'sup',                          //'上标',
        '-',
        'quote',                        //'引用',
        'unorderedList',                //'无序列表',
        'orderedList',                  //'有序列表',
        'codeRow',                      //'行内代码',
        'code',                         //'块级代码',
        'link',                         //'链接',
        'image',                        //'图片',
        'table',                        //'表格',
        'katex',                        //'公式', 
        '-',
        'revoke',                       //'后退一步',
        'next',                         //'前进一步',
        'save',                         //'保存',
        '=',
        'pageFullscreen',               //'页面内全屏',
        'fullscreen',                   //'屏幕全屏',
        'preview',                      //'内容预览',
        'htmlPreview',                  //'html代码预览',
        'catalog',                      //'目录'
      ],
      toolbarsExc: [],
      chooseFile: null
    }
  },
  computed: {
    acceptsList () {
      let _list = []
      _list = this.fileObject.accepts['MD']
      return _list
    },
    allAcceptsList () {
      let _list = []
      Object.keys(this.fileObject.accepts).map(t => {
        _list = _list.concat(this.fileObject.accepts[t].accept || [])
      })
      return {
        accept: _list || ['*'],
        hint: '仅支持 ' + _list.join('，') + ' 格式'
      }
    }
  },
  methods: {
    handleSave () {
      this.saveMdFile(this.closeDialog)
    },
    handleExceed () {
      this.$message.warning('只能选择单个文件')
      this.chooseFile = null
      this.form.fileName = null
    },
    uploadBefore (file) {
      let FileExt = file.name.replace(/.+\./, '.')
      if (this.acceptsList.accept && (this.acceptsList.accept[0] !== '*') && (this.acceptsList.accept.indexOf(FileExt.toLowerCase()) === -1)) {
        this.$message({
          type: 'warning',
          message: this.acceptsList.hint + '！'
        })
      } else {
        if (file.name.length > 200) {
          this.$message({
            type: 'warning',
            message: '资源名称不能超过200个字符'
          })
        } else {
          if (FileExt.toLowerCase() === '.md') {
            if (file.size / 1024 / 1024 >= 1) {
              this.$message({
                type: 'warning',
                message: 'Markdown资源大小不能超过1M！'
              })
              return false
            }
          }
          // 上传是否为单个文件
          this.chooseFile = file
          let that = this
          this.fileObject.getFileContentText(this.chooseFile, (str) => {
            that.text = str
          })
        }
      }
      return false
    },
    closeDialog () {
      this.$emit('closeDialog')
    },
    closeDrawer (done) {
      if (this.defaultText !== this.text) {
        this.mmsgBox({
          title: '提示信息',
          text: `markdown文件内容有变更，请确认是否保存?`,
          showClose: false,
          actions: [
            {
              key: 'true',
              text: '确定'
            },
            {
              key: 'false',
              text: '取消'
            }
          ]
        }).then(result => {
          if (result) {
            this.saveMdFile(done)
          } else {
            done()
          }
        })
      } else {
        done()
      }
    },
    async onUploadImg (files, callback) {
      let that = this
      const resList = await Promise.all(
        Array.from(files).map((file) => {
          return new Promise((rev, rej) => {
            that.fileObject.uploadFileNoTag(file)
              .then((res) => rev(res.data))
              .catch((error) => rej(error));
          });
        })
      );
      callback(resList.map((item) => {
        let arr = item.data || [null]
        let fileObj = arr[0]
        that.concatIds.push(fileObj.eid)
        return that.fileObject.getFileUrl(fileObj.eid)
      }));
    },
    saveMdFile (cb) {
      let file = this.fileObject.saveTextToMdFile(this.text)
      file.name = '实验手册.md'
      this.fileObject.uploadFileNoTag(file)
        .then((res) => {
          this.loading = false
          if (res.data.code === 200) {
            // 单个文件上传异常处理
            let arr = res.data.data || [null]
            let fileObj = arr[0]
            this.$emit('setFile', fileObj, this.concatIds, cb)
          } else {
            this.$message.error('保存文件失败！')
          }
        })
        .catch(() => {
          this.loading = false
          this.$message.error('保存文件失败！')
        });
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~/styles/base.scss";
.btn-list {
  height: 36px;
  margin-top: -16px;
}
.md-detail-view {
  height: calc(100% - 20px);
  // :deep(.md-content) {
  //   height: calc(100% - 44px);
  // }
  :deep(#md-editor-v3-textarea) {
    border-right: 1px solid #e6e6e6;
  }
}
</style>